package com.video.moderation.controller;

import com.video.moderation.constant.SecurityConstants;
import com.video.moderation.entity.SysMember;
import com.video.moderation.entity.dto.Result;
import com.video.moderation.entity.model.ChangePwdForm;
import com.video.moderation.entity.model.LoginForm;
import com.video.moderation.exception.ServiceException;
import com.video.moderation.repository.SysMemberRepository;
import com.video.moderation.service.SysMemberService;
import com.video.moderation.utils.JwtUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(path = "/member", produces = "application/json;charset=utf-8")
public class SysMemberController {

    @Autowired
    private SysMemberService sysMemberService;

    @Autowired
    private SysMemberRepository sysMemberRepository;

    @Resource
    private JwtUtils jwtUtils;

    @PostMapping("/login")
    public Result login(@RequestBody LoginForm loginForm, HttpServletRequest request, HttpServletResponse response) {
        return sysMemberService.login(loginForm.getMemberNum(), loginForm.getPassword(), request, response);
    }

    @PostMapping("/logout")
    public Result logout(HttpServletRequest request, HttpServletResponse response) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            new SecurityContextLogoutHandler().logout(request, response, authentication);
        }
        return Result.success();
    }

    @PostMapping("/changePassword")
    public Result changePassword(@RequestBody ChangePwdForm changePwdForm, HttpServletRequest request) {
        String originPassword = changePwdForm.getOriginPassword();
        String newPassword = changePwdForm.getNewPassword();
        if (originPassword.equals(newPassword)) throw new ServiceException("两个密码一致");

        String token = request.getHeader(SecurityConstants.AUTHORIZATION);
        Integer memberId = (Integer) jwtUtils.getClaims(token).get(SecurityConstants.MEMBER_ID);

        SysMember member = sysMemberRepository.findById(memberId).orElse(null);
        if (!BCrypt.checkpw(originPassword, member.getPassword())) throw new ServiceException("原始密码不正确");
        
        if(member.getPassword().length() < 6 || member.getPassword().length() >10) throw new ServiceException("新密码不符合规范");
        
        member.setPassword(BCrypt.hashpw(newPassword, BCrypt.gensalt()));
        sysMemberRepository.save(member);
        return Result.success();
    }

}
